'use client'

import React, { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useToast } from '@/hooks/use-toast'

export default function LoginPage() {
  const { toast } = useToast()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const router = useRouter()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')

    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, password }),
      })

      const data = await response.json()
      
      if (!response.ok) {
        throw new Error(data.error || '登录失败，请检查您的凭证')
      }

      if (!data.token || !data.id || !data.email) {
        throw new Error('登录响应数据不完整')
      }

      try {
        localStorage.setItem('token', data.token)
        localStorage.setItem('userid', data.id)
        localStorage.setItem('email', data.email)
        localStorage.setItem('name', data.name)
        
        window.location.href = '/topics'

      } catch (storageError) {
        console.error('本地存储失败:', storageError)
        throw new Error('无法保存登录信息，请检查浏览器设置')
      }
    } catch (err: any) {
      setError(err.message || '登录失败，请重试')
      toast({
        title: 'Error',
        description: err.message || '登录失败，请重试',
        variant: 'destructive',
      })
    }
  }

  return (
    <div className="max-w-md mx-auto mt-10">
      <h1 className="text-2xl font-bold mb-4">登录</h1>
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <Label htmlFor="email">邮箱</Label>
          <Input
            id="email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </div>
        <div>
          <Label htmlFor="password">密码</Label>
          <Input
            id="password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
        </div>
        <Button type="submit" className="w-full">
          登录
        </Button>
      </form>
      <div className="mt-4 text-center">
        <span className="text-sm text-gray-600">没有账户？</span>
        <Button 
          variant="link" 
          className="text-sm p-0"
          onClick={() => router.push('/register')}
        >
          立即注册
        </Button>
      </div>
    </div>
  )
}